#include "Bluetooch.h"
#include <stdio.h>
#include "System.h"

char blue_buf[128];
int8_t blue_Flag = 0;

void Blue_GPIOInit(void)
{
	// USART3
	// PA10-TX,PA11-RX
	GPIO_InitTypeDef GPIO_InitStructure;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

}

void Bluetooth_init(int baud)
{

	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStrcuture;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

	Blue_GPIOInit();

	USART_InitStructure.USART_BaudRate = baud;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	USART_Init(USART3, &USART_InitStructure);

	NVIC_InitStrcuture.NVIC_IRQChannel = USART3_IRQn;
	NVIC_InitStrcuture.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStrcuture.NVIC_IRQChannelSubPriority = 2;
	NVIC_InitStrcuture.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStrcuture);

	USART_Cmd(USART3, ENABLE);

	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);

	while (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET)
		;
}

void Bluetooth_Send(unsigned char *str)
{
	while (*str != '\0')
	{
		USART_SendData(USART3, *str);
		while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET)
			;
		str++;
	}
}


void USART3_IRQHandler(void)
{
	static int i = 0;
	if (USART_GetITStatus(USART3, USART_IT_RXNE) == SET)
	{

		blue_buf[i++] = USART_ReceiveData(USART3);
		if (i >= 128 || blue_buf[i - 1] == '#')
		{
			blue_buf[i - 1] = '\0';
			i = 0;
			blue_Flag = 1;
			// bt_parse_data(blue_buf);
		}

		USART_ClearITPendingBit(USART3, USART_IT_RXNE);
	}
}
